<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>图片上传</title>
    <link
      href="/bootstrap.min.css"
      rel="stylesheet"
    />
    <script src="/bootstrap.bundle.min.js"></script>
    <script src="/axios.min.js"></script>
  </head>
  <body
    class="d-flex flex-column align-items-center justify-content-center min-vh-100 bg-light p-4"
  >
    <!-- 加载动画 -->
    <div
      id="loading"
      class="position-relative mb-3 p-3 bg-dark text-white rounded"
      style="display: none; z-index: 10"
    >
      加载中...
    </div>

    <!-- 图片展示容器 -->
    <div
      id="background-container"
      class="border bg-white rounded mb-4"
      style="
        width: 200px;
        aspect-ratio: 1;
        background-size: contain;
        background-repeat: no-repeat;
        background-position-x: center;
      "
    ></div>

    <!-- 上传和录入按钮 -->
    <div class="d-flex align-items-center gap-2">
      <button
        type="button"
        class="btn btn-primary"
        id="upload-label"
        data-bs-toggle="modal"
        data-bs-target="#uploadModal"
      >
        搜索人脸
      </button>
      <button type="button" class="btn btn-success d-none" id="record-button">
        录入人脸
      </button>
    </div>
    <!-- 隐藏的文件选择器 -->
    <input type="file" class="d-none" id="bg" />

    <!-- 模态框 -->
    <div class="modal fade" id="registerModal" tabindex="-1" aria-hidden="true">
      <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="confirmModalLabel">确认</h5>
            <button
              type="button"
              class="btn-close"
              data-bs-dismiss="modal"
              aria-label="关闭"
            ></button>
          </div>
          <div class="modal-body">未匹配到结果，是否显示注册您的Face?</div>
          <div class="modal-footer">
            <button
              type="button"
              class="btn btn-secondary"
              data-bs-dismiss="modal"
            >
              取消
            </button>
            <button type="button" class="btn btn-primary" id="modal-confirm">
              确定
            </button>
          </div>
        </div>
      </div>
    </div>
    <!-- 显示搜索结果的容器 -->
    <div id="search-results" class="mt-4 d-none">
      <h4>匹配结果:</h4>
      <ul id="result-list" class="list-group">
        <!-- 搜索结果项 -->
      </ul>
    </div>

    <!-- 显示注册后图片的容器 -->
    <div id="register-success" class="mt-4 d-none">
      <h4>录入成功:</h4>
      <div id="result-images" class="d-flex justify-content-around gap-3">
        <!-- 注册后显示的图片 -->
      </div>
    </div>

    <!-- 文本输入模态框 -->
    <div
      class="modal fade"
      id="inputTextModal"
      tabindex="-1"
      aria-hidden="true"
    >
      <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">请输入昵称</h5>
            <button
              type="button"
              class="btn-close"
              data-bs-dismiss="modal"
              aria-label="关闭"
            ></button>
          </div>
          <div class="modal-body">
            <label for="additionalText" class="form-label">昵称:</label>
            <input
              type="text"
              id="additionalText"
              class="form-control"
              placeholder="请输入文字..."
            />
          </div>
          <div class="modal-footer">
            <button
              type="button"
              class="btn btn-secondary"
              data-bs-dismiss="modal"
            >
              取消
            </button>
            <button type="button" class="btn btn-primary" id="text-confirm">
              确定
            </button>
          </div>
        </div>
      </div>
    </div>

    <script>
      // 用于存储选择的文件
      let selectedFile = null;
      const modalElement = document.getElementById("registerModal");
      const modalInstance = bootstrap.Modal.getOrCreateInstance(modalElement);

      const inputModalElement = document.getElementById("inputTextModal");
      const inputModalInstance =
        bootstrap.Modal.getOrCreateInstance(inputModalElement);
      // 设置背景图片
      function setBg(url) {
        const bgContainer = document.getElementById("background-container");
        bgContainer.style.backgroundImage = `url(${url})`;
      }

      // 上传文件
      // 上传文件
      function uploadFile(url, file, otherParams = {}) {
        const fd = new FormData();
        fd.append("file", file);

        // 添加其他参数到 FormData
        Object.keys(otherParams).forEach((key) => {
          fd.append(key, otherParams[key]);
        });

        return axios.post(url, fd);
      }

      // 显示/隐藏加载动画
      function toggleLoading(
        show,
        text = "图片搜索中...",
        autoHideTime = null
      ) {
        const loading = document.getElementById("loading");
        if (show) {
          loading.textContent = text; // 设置显示的文字
          loading.style.display = "block";
          if (autoHideTime) {
            setTimeout(() => {
              loading.style.display = "none";
            }, autoHideTime * 1000); // 将秒数转换为毫秒
          }
        } else {
          loading.style.display = "none";
        }
      }

      // 显示搜索结果
      function showSearchResults(matches) {
        const resultList = document.getElementById("result-list");
        resultList.innerHTML = "";

        matches.forEach((match) => {
          // 创建结果容器
          const listItem = document.createElement("li");
          listItem.className =
            "list-group-item d-flex justify-content-start align-items-center flex-wrap gap-3";

          // 添加用户名和用户ID
          const userInfo = document.createElement("div");
          userInfo.className = "mb-2";
          const scoreText =
            match.score === 0 ? "完美匹配" : match.score || "未知";
          userInfo.innerHTML = `
                <strong>用户名:</strong> ${match.userName || "未知"}<br>
                <strong>用户ID:</strong> ${match.userId || "未知"}<br>
                <strong>用户评分:</strong> ${scoreText}<br>
            `;
          listItem.appendChild(userInfo);

          // 创建图片行容器
          const imageRow = document.createElement("div");
          imageRow.className =
            "d-flex justify-content-start align-items-center gap-3";
          // 遍历每个 match 元素中的两张图片
          [match.faceFeatureUrl, match.faceUrl].forEach((image, idx) => {
            const img = document.createElement("img");
            img.src = image;
            img.alt = `搜索结果${idx}`;
            img.className = "img-thumbnail";
            img.style.maxWidth = "150px";
            img.style.maxHeight = "150px";
            img.style.objectFit = "contain";
            imageRow.appendChild(img);
          });
          listItem.appendChild(imageRow);
          resultList.appendChild(listItem);
        });

        document.getElementById("search-results").classList.remove("d-none");
      }
      // 删除搜索结果
      function removeSearchResults() {
        const resultList = document.getElementById("result-list");
        resultList.innerHTML = "";
        document.getElementById("search-results").classList.add("d-none");
      }

      // 显示注册后图片
      function showRegisterImages(images) {
        const resultImagesContainer = document.getElementById("result-images");
        resultImagesContainer.innerHTML = "";

        images.slice(0, 2).forEach((image) => {
          const img = document.createElement("img");
          img.src = image;
          img.alt = "Result Image";
          img.className = "img-thumbnail";
          img.style.maxWidth = "150px";
          img.style.maxHeight = "150px";
          img.style.objectFit = "contain";
          resultImagesContainer.appendChild(img);
        });

        document.getElementById("register-success").classList.remove("d-none");
      }
      // 删除注册后图片
      function removeRegisterImages() {
        const resultImagesContainer = document.getElementById("result-images");
        resultImagesContainer.innerHTML = "";
        document.getElementById("register-success").classList.add("d-none");
      }

      function startFaceInit(userName = "") {
        if (!selectedFile) return;

        toggleLoading(true, "正在录入...");

        uploadFile("/face/faceInit", selectedFile, { userName })
          .then((res) => {
            if (res.data.code == 0) {
              toggleLoading(false);
              toggleLoading(true, "录入成功！再次搜索请点击搜索人脸", 3);
              const result = res.data.data;
              console.info("录入结果:", result);
              removeSearchResults();
              removeRegisterImages();
              showRegisterImages([result.faceFeatureUrl, result.faceUrl]);
            } else {
              const message = res.data.message || "录入失败，请稍后再试！";
              toggleLoading(true, message, 1.5);
            }
          })
          .catch((err) => {
            toggleLoading(false);
            console.error("录入失败：", err);
            const message = "服务器错误，请稍后再试";
            toggleLoading(true, message, 1.5);
          });
      }

      // 上传按钮点击事件，触发文件选择
      document.getElementById("upload-label").addEventListener("click", () => {
        document.getElementById("bg").click();
      });

      // 文件选择器事件绑定
      document.getElementById("bg").addEventListener("change", (e) => {
        removeSearchResults();
        removeRegisterImages();
        const file = e.target.files[0];
        if (!file) return;

        // 仅允许 PNG 和 JPG 格式
        const allowedTypes = ["image/png", "image/jpeg"];
        if (!allowedTypes.includes(file.type)) {
          alert("仅支持上传 PNG 或 JPG 格式的图片！");
          e.target.value = ""; // 清空选择的文件
          return;
        }
        // 验证文件大小
        if (file.size > 2 * 1024 * 1024) {
          alert("图片大小不能超过 2MB");
          return;
        }
        setBg(URL.createObjectURL(file)); // 将本地文件显示
        selectedFile = file;
        toggleLoading(true); // 显示加载动画

        // 上传文件
        uploadFile("/face/faceSearch", file)
          .then((result) => {
            toggleLoading(false);
            console.info("返回结果:", result);
            if (result.data.code == 0) {
              const macthes = result.data.data;
              console.info("图片搜索返回结果:", macthes);
              if (macthes.length > 0) {
                // 搜索到了结果
                showSearchResults(macthes);
                document.getElementById("record-button").classList.remove("d-none");
              } else {
                // 未搜索到结果，显示弹窗
                modalInstance.show();
              }
            } else {
              const message = result.data.message || "服务器错误，请稍后再试";
              toggleLoading(true, message, 1.5);
              document.getElementById("record-button").classList.add("d-none");
            }
          })
          .catch((error) => {
            toggleLoading(false);
            console.error("图片上传失败:", error);
            const message = "图片上传失败";
            toggleLoading(true, message, 1.5);
            document.getElementById("record-button").classList.add("d-none");
          })
      });

      // 确认注册
      document.getElementById("modal-confirm").addEventListener("click", () => {
        modalInstance.hide();
        inputModalInstance.show();
      });

      // 录入按钮点击事件
      document.getElementById("record-button").addEventListener("click", () => {
        inputModalInstance.show();
      });

      // 处理输入文字后的逻辑
      document.getElementById("text-confirm").addEventListener("click", () => {
        const additionalText = document
          .getElementById("additionalText")
          .value.trim();
        if (!additionalText) {
          alert("请输入昵称！");
          return;
        }

        inputModalInstance.hide();
        startFaceInit(additionalText);
      });
    </script>
  </body>
</html>
